home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d1 / bastips2.arc / FASTBASC.TXT < prev    next >
Text File  |  1988-11-29  |  12KB  |  247 lines

  1.                          Fast and BASIC
  2.              (PC World September 1986 by Greg Perry)
  3.  
  4.      You won't start an argument by contending that BASIC has become
  5. the computer language of the masses.  You might get a few takers,
  6. however, if you insist that it made it on its merits, with no help
  7. from firmware.
  8.      If you held your ground, you'd best your opposition.  BASIC
  9. represents an unusually successful attempt to be many things to many
  10. people.  It's comprehensive yet accessible, boasting features that
  11. even some mainframe languages lack.  Although BASIC has its inelegant,
  12. unstructured side, it's nonetheless easy to use.  It relies on
  13. straightforward English statements -- such as PRINT and INPUT -- but
  14. is capable of complex operations, including creating and updating both
  15. sequential and random access data files.
  16.      Like most BASIC users, you probably tend to write programs as
  17. fast as you can -- but you may well be bypassing ways to write the
  18. fastest programs possible.  BASIC veterans and fledgling programmers
  19. alike can profit from techniques that build programs for speed.
  20.      Computers cannot, of course, understand BASIC or any other high-
  21. level language directly.  Their lexicon is limited to machine language
  22. instructions, encoded as 1s and 0s.  Fortunately, because human beings
  23. make the machines (and the rules), there's no compulsion to convey
  24. commands as strange, symbolic representations of bits and bytes.  Thus,
  25. high-level languages use instructions that mere mortals can read and
  26. save a ASCII files.  A single instruction in a high-level language
  27. represents a series of elemental machine tasks.  Interpreters and
  28. compilers enter the scene as agents that translate our instructions
  29. into commands the computer understands.
  30.      Interpreted BASIC is a language of immediate gratification.
  31. Commands execute without compilation or linkages, and programs, once
  32. loaded, execute immediately.  That's the case because interpreted
  33. BASIC programs are translated as they run.  An interpreter reads a
  34. line of code, translates it to machine instructions, and executes
  35. those instructions.  It then reads, translates, and executes the next
  36. logical line in the program, even if it has processed that line before
  37. (for example, in a loop of instructions).  A compiler, on the other
  38. hand, reads and translates a BASIC program as an entity, writing to
  39. disk an entirely new file called an object code file.  The object
  40. code file is then linked to other compiled program modules with a
  41. special program called a linker.  Even if you have no other compiled
  42. program modules, you must use the linker to create a third disk file,
  43. the executable (.EXE) file.
  44.      While the compilation process is time-consuming, it generates
  45. code that executes in a flash; interpretive code, by contrast, is
  46. ready to run and can be edited easily and quickly, but executes
  47. slowly.
  48.      Most BASICs (including the PC's) are interpreted rather than
  49. compiled.  While interpreted BASIC programs may be compiled, compilers
  50. are generally used only by professional programmers.  Interpreters
  51. have become a hit with novice programmers because interpreted BASIC
  52. programs are easy to tinker with and rerun.  That interactive
  53. environment is conducive to understanding and experimentation.  The
  54. trade-off is execution speed: A compiled programs is several orders
  55. of magnitude faster than an interpreted one.
  56.      If SAMPLE1.BAS were to be compiled, for example, the entire
  57. program would be read and (except the REMarks in lines 5 and 15)
  58. translated into object code and stored on disk.  (The compiler
  59. acknowledges the REMark lines only once and doesn't bother to compile
  60. any such lines of code.)  The object code would then be linked to
  61. produce an .EXE file.
  62.  
  63. SAMPLE1.BAS:
  64.  
  65. 5 REM *** Program to print the numbers 1 through 10
  66. 10 I=1
  67. 15 REM --- Print the number
  68. 20 PRINT I
  69. 30 IF I>=10 THEN 60
  70. 40 I=I+1
  71. 50 GOTO 15
  72. 60 END
  73.  
  74.      In contrast, if the program were run through an interpreter, each
  75. line would be individually translated and executed.  Even REMarks are
  76. first identified and then ignored every time program execution loops
  77. through a REMark line.  SAMPLE2.BAS requires some 500 interpretations
  78. of the REM statements within its loop.  It's no wonder that interpreted
  79. BASIC incurs major speed penalties.  But once you appreciate the
  80. strengths and limitations of interpreters, it's possible to optimize
  81. interpreted BASIC programs.
  82.  
  83. SAMPLE2.BAS:
  84.  
  85. 5 REM *** Interpreting REMarks slows
  86. 6 REM *** down BASIC programs
  87. 10 DEFINT I
  88. 20 FOR I=1 TO 100
  89. 25 REM --- This REMark takes up time
  90. 26 REM --- So does this one
  91. 27 REM arkable, isn't it?
  92. 30 PRINT I
  93. 35 REM -- We are almost done
  94. 36 REM -- with the REMarks
  95. 40 NEXT I
  96. 50 END
  97.  
  98.     Obviously, eradicating all REM statements speeds program execution.
  99. Good documentation, however, is vital to your ability to understand and
  100. modify a program.  So in lieu of banishing REMs completely, you can
  101. purge them from a run-time version of your handiwork.  Documentation
  102. should be written as the program is developed, not afterward, and a
  103. thoroughly REMarked-up version of the program will serve as a
  104. permanent reference.  In a nutshell: When writing a BASIC program, use
  105. REMarks liberally; once the program is written and debugged, copy it
  106. (giving it a different name) and eliminate the REMs.
  107.  
  108. BASIC Programming Tips to Live By:
  109.  
  110. - Delete REM statements from your code
  111. - Declare all variables with a DEFtype statement before the variables
  112.   are used
  113. - Keep variable names short
  114. - Use variables instead of numeric or string constants
  115. - Place DATA statements at the beginning of a program
  116. - Put frequently called subroutines near the beginning of a program
  117. - Use the colon to combine as many statements per program line as you
  118.   can
  119. - Eliminate all unnecessary spaces
  120. - Don't use extraneous words in statements
  121.  
  122.      Our quest for efficiency also entails declaring all variables as
  123. integer, single-precision, double-precision, or string variables by
  124. means of DEF statements at the start of the program.  For integer
  125. routines, failure to declare a variable's type has the unhappy
  126. consequence of causing numeric variables to default to single-precision
  127. variables.  In such a situation, every time a FOR...NEXT loop is
  128. interpreted, for example, the index variable (such as the variable I
  129. in FOR I = 1 TO 10) would be carried out to six decimal places -- a
  130. needless squandering or processing time.
  131.      Some programmers prefer to declare a variable's type explicitly
  132. when it's used, rather than relying on the global declaration of a DEF
  133. statement.  You could, for instance, declare I as an integer by
  134. following it with the percent symbol at every occurrence in the
  135. program.  Although this approach beats letting the variable default
  136. to single-precision, you're still asking the computer to spend clock
  137. ticks interpreting I%.  Program execution is quicker if you declare I
  138. as an integer-precision variable with the DEFINT I statement.
  139.      With string variables, even die-hard, speed-conscious BASIC
  140. programmers tend to use H$ rather than declaring H as a string in a
  141. single DEFSTR H statement.  Like the I% approach, however, H$ exacts
  142. its price in slower execution.
  143.      Furthermore, although IBM BASIC permits variable names of up to
  144. 40 characters, the shorter the name, the more efficient the
  145. interpretation.  The drawback of brevity, however, is that the code
  146. is less informative.
  147.      Each time your program uses a numeric constant, you force BASIC
  148. to add steps to its interpretive dance.  By examining the ASCII
  149. representation of each digit, sign, and decimal point, the interpreter
  150. converts the constant to the special format BASIC uses to store numeric
  151. values.  Every time the interpreter encounters a numeric constant, the
  152. dance begins anew.
  153.      You can forego these gyrations by assigning a constant to a
  154. variable and using that variable throughout the program.  Once the
  155. number is converted and assignment made, BASIC simply looks up the
  156. variable's value in an internal table.  For an example of this,
  157. compare SAMPLE3.BAS and SAMPLE4.BAS; the latter routine shows that pi
  158. is better handled as the variable PI than as the value 3.14159.
  159.  
  160. SAMPLE3.BAS:
  161.  
  162. 5 REM *** Interpreting numeric constants slows down BASIC programs
  163. 10 DEFINT I
  164. 20 FOR I=1 TO 100
  165. 30 PRINT 3.14159*I
  166. 40 NEXT I
  167. 50 END
  168.  
  169. 5 REM ** Using a variable in place of a constant speeds up BASIC progs
  170. 10 DEFINT I
  171. 20 PI=3.14159
  172. 30 FOR I=1 TO 100
  173. 40 PRINT PI*I
  174. 50 NEXT I
  175. 60 END
  176.  
  177.      You can squeeze similar speed improvements from your code when
  178. working with string constants.  Assigning such a constant to a variable
  179. once -- and henceforth using that variable in place of the constant --
  180. shortens the program and eliminates multiple interpretations.
  181.      Arranging statements in a sensible order is often the soul of an
  182. efficient program.  Any time you use a set of READ and DATA statements,
  183. put the DATA statements as close to the top of the program as possible.
  184. When a READ statement is executed, the interpreter searches the program
  185. from the beginning to find the next unused DATA line, even though the
  186. DATA statements may directly follow the READ statements.
  187.      Likewise, when a program reaches a GOSUB, the BASIC interpreter
  188. goes to the beginning of the program and reads line numbers until it
  189. hits the subroutine's line number.  BASIC simply isn't capable of
  190. proceeding directly to the line of code called.  Therefore, it's a
  191. good idea to place the most frequently used subroutines ahead of
  192. routines you use less often.  In doing so, you painlessly minimize
  193. BASIC's work when a program reaches a GOSUB.  Obvious as it seems,
  194. this simple procedure is usually overlooked.
  195.      Presentation of BASIC staetments can also bolster program
  196. performance.  You can pack several BASIC commands into a single
  197. logical line (a maximum of 255 characters) by separating them with
  198. a colon.  SAMPLE5.BAS, for instance, shows a seven-line program;
  199. SAMPLE6.BAS shows the same program shortened to just two lines.  The
  200. second arrangement yields the same result as the first but does it
  201. faster, simply because its statements have been combined.  With the
  202. colon carrying the load, the interpreter no longer needs to decode
  203. line numbers.
  204.  
  205. SAMPLE5.BAS:
  206.  
  207. 5 REM *** This program is big and thus slow
  208. 10 CLS:PRINT "Hello."
  209. 20 PRINT
  210. 30 PRINT "Who are you";
  211. 40 INPUT N$
  212. 50 PRINT "Well, "N$", I'm pleased to meet you."
  213. 60 END
  214.  
  215. SAMPLE6.BAS:
  216.  
  217. 5 REM ** This program is more compact and thus faster
  218. 10 CLS:PRINT "Hello.":PRINT:PRINT "Who are you";:INPUT N$:PRINT "Well,
  219. "N$", I'm pleased to meet you.":END
  220.  
  221.      Granted, the two-line program is a bit hard to decipher (which is
  222. why your original need not be this compact), but it leaves the seven-
  223. line version at the starting gate.  Note also that the two-liner
  224. doesn't contain a single superfluous space.
  225.      Spaces can't be eliminated entirely.  You'll need them (or other
  226. delimiters) to separate BASIC commands and variable names.  For
  227. instance, the interpreter does not understand PRINTI to be PRINT I.
  228. Nor can you jettison spaces from string constants.  Assignment
  229. statements, however, should read something like A=B+C instead of A = B
  230. + C.  Wiping out spaces may seem trivial, but the interpreter treats
  231. spaces just as it does alphanumeric symbols.  As a rule, the fewer
  232. spaces, the better.
  233.     On the whole, BASIC programmers are savvy enough to avoid inserting
  234. redundant words and commands.  Most have been omitting the redundant
  235. LET statement for so long they've progably forgotten LET exists.
  236. Obviously, LET A=B is slower and less compact than A=B, which does the
  237. same thing.  On the other hand, a few less obvious BASIC statements --
  238. like OPEN -- also lend themselves to shortcuts.  OPEN O,1,filename can
  239. do the work of OPEN filename FOR OUTPUT AS #1 LEN=128 in less than half
  240. the space.
  241.     This litany of tips is just the beginning of resourceful, efficient
  242. programming.  Most of the code you'll be generating in this way isn't
  243. pretty and doesn't make for especially readable listings.  But the only
  244. thing likely to slow you down is the edict that you keep both sleek and
  245. well-documented versions of your programs.
  246.  
  247.